﻿using System.Collections.Specialized;
using System.Windows;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using TS3ServerManager.BL;
using TS3ServerManager.BL.Eventing;
using TS3ServerManager.Controls;
using System.Linq;

namespace TS3ServerManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        #region Constructor

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        #endregion

    	#region Non Public Methods

    	private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    	{
    		ConnectionArea.StartConnection += ConnectionArea_StartConnection;         
    	}

    	private void ConnectionArea_StartConnection(object sender, ConnectEventArgs e)
    	{
			foreach (TabItem tabItem in ServerTabsControl.Items)
			{
				ServerConnectInfo tabsConnectInfo = (ServerConnectInfo)((ServerControl)tabItem.Content).DataContext;

				if (tabsConnectInfo.Host == e.ConnectInfo.Host && tabsConnectInfo.QueryPort == e.ConnectInfo.QueryPort && tabsConnectInfo.Username == e.ConnectInfo.Username)
				{
					tabItem.IsSelected = true;
					MessageBox.Show("A connection to the same server with the same credentials already exist.");
					return;
				}
			}

    		ServerConnectInfo connectInfo = e.ConnectInfo.Clone();
			CloseableTabItem newTab = new CloseableTabItem { Content = new ServerControl { DataContext = connectInfo }, Header = connectInfo.Host };
			newTab.CloseTab += ServerTab_Closed;
			ServerTabsControl.SelectedIndex = ServerTabsControl.Items.Add(newTab);
    	}

		private void ServerTab_Closed(object sender, RoutedEventArgs e)
		{
			ServerTabsControl.Items.Remove(sender);
			((ServerControl) ((CloseableTabItem) sender).Content).Dispose();
		}

    	private void ExitMenu_Click(object sender, RoutedEventArgs e)
    	{
    		Exit();
    	}

    	private void AboutMenu_Click(object sender, RoutedEventArgs e)
    	{
    		MessageBox.Show("Nothing here yet ;)");
    	}

    	private static void Exit()
    	{
    		App.Current.Shutdown();
    	}

    	#endregion
    }
}